﻿using SuperX.Common.Log;
using SuperX.SuperSocket.Socket.Transfer.Client;
using SuperX.SuperSocket.Socket.Transfer.Client.DownLoad;
using System;
using System.IO;
using System.Threading.Tasks;

namespace SuperX.SuperSocket.Socket.Transfer.Client.DownLoad.Command
{
    internal class DoCheckExist : DownloadCommandBase
    {
        public override void ExecuteCommand(DownLoadEngine session, TransferCommandInfo commandInfo)
        {
            try
            {
                ConsoleLogHelper.Debug("DoCheckExist");
                FileInfo serverConfigInfo = SerializeHelp.Deserialize<FileInfo>(commandInfo.Data);
                if (serverConfigInfo.FileSize == -1)
                {
                    Logger.Error($"{serverConfigInfo.FileName} file is not exist");
                    session.OnTransferFileNotExist(new TransferFileNotExistEventArgs(serverConfigInfo.FileName));
                    session.Dispose();
                    return;
                }

                session.DownloadInfo = serverConfigInfo;
                string saveName = Path.GetFullPath(serverConfigInfo.SaveName);
                string saveTempName = saveName + Config.TempSuffix;
                string saveNamePath = Path.GetDirectoryName(saveName);
                if (!Directory.Exists(saveNamePath))
                    Directory.CreateDirectory(saveNamePath);
                if (File.Exists(saveTempName))
                {
                    File.Delete(saveTempName);
                    //session.m_fileStream = new FileStream(saveTempName, FileMode.Open, FileAccess.Write);
                }
                session.m_fileStream = new FileStream(saveTempName, FileMode.Create, FileAccess.Write);
                session.m_fileStream.SetLength(serverConfigInfo.FileSize);
                byte[] data = SerializeHelp.Serialize(serverConfigInfo);
                session.SendData(UpLoadOP.DoDownload, data, 0, data.Length);
            }
            catch (Exception ex)
            {
                ConsoleLogHelper.Debug(ex.ToString());
                session.OnTransferError(new TransferErrorEventArgs(ex));
                //ex.ToString();
                //error to do;
            }
        }

        public override string Name
        {
            get
            {
                return UpLoadOP.DoCheckExist.ToString();
            }
        }
    }
}